package com.xunfang.aspect;

import com.xunfang.bean.Log;
import com.xunfang.common.Result;
import com.xunfang.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author yellow Docter
 * @date 2023 -11-13
 * @desc 日志记录
 */
@Aspect
@Component
public class MyLogAspect {

    @Autowired
    private LogService logService;

    @Pointcut("execution(* com.xunfang.controller.*.*(..))")
    public void pct(){
    }

    @Around(value = "pct()")
    public Object around(ProceedingJoinPoint pjp){

        //执行目标方法
        Object result = null;
        try {
            result = pjp.proceed();

            //进行日志的 存储到 db中
            insertLog(pjp,result);

        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        return result;
    }

    /**
     * 日志的存储
     * @param pjp
     * @param result
     */
    private void insertLog(ProceedingJoinPoint pjp, Object result) {

        //存储的数据
        //拿到请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();

        //请求方式
        String reqType = request.getMethod();

        //请求路径
        String reqUrl= request.getRequestURL().toString();

        //获取ip
        String ip = request.getRemoteAddr();

        //全类名
        // pjp.getTarget() 通过连接点  (Controller的全类名)
        String fullClass = pjp.getTarget().getClass().getName();
        // 获取当前执行的方法

        //方法的名称
        // pjp.getSignature();  获取了连接点的方法的签名
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String method = signature.getMethod().getName();

        //请求参数
        Object[] args = pjp.getArgs();
        String reqParams = Arrays.toString(args);

        Log log = new Log();
        log.setReqType(reqType);
        log.setIp(ip);
        log.setReqUrl(reqUrl);
        log.setFullClass(fullClass);
        log.setMethod(method);
        log.setReqParams(reqParams);
        log.setRespData(result.toString());

        System.out.println("日志记录:log = " + log);
        //存储日志到 db 中
        logService.saveLog(log);
        
    }

}
